package com.gengzp.mq.client.tools;

import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @ClassName MqHttpRequester
 * @Description mq消息队列 http 请求器（使用Java自带HttpClient）
 * @Author gengzp
 * @Date 2025/9/24 14:45
 */
@Component
public class MqHttpRequester {

    private final HttpClient httpClient;
    private static MqHttpRequester mqHttpRequester;

    /**
     * 媒体请求类型 (统一使用 json 格式, utf-8)
     */
    private static final String JSON_MEDIA_TYPE = "application/json; charset=utf-8";

    // 注入Java HttpClient（对应配置类中的mqHttpClient Bean）
    private MqHttpRequester(HttpClient mqHttpClient) {
        this.httpClient = mqHttpClient;
    }

    @PostConstruct
    public void init() {
        mqHttpRequester = this;
    }

    /**
     * 发送带有自定义请求头的post请求
     *
     * @param url         请求地址url
     * @param requestBody 请求参数
     * @param headers     请求头
     * @param typeRef     响应结果类型
     * @param <T>         响应结果类型
     * @return 响应结果
     */
    public static <T> T post(String url,
                             Object requestBody,
                             Map<String, String> headers,
                             TypeReference<T> typeRef) throws RuntimeException {
        try {
            // 1.转换请求体为JSON字符串
            String jsonBody = MqJsonConverter.convertObjectToJson(requestBody);

            // 2.构建请求
            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", JSON_MEDIA_TYPE)
                    .POST(HttpRequest.BodyPublishers.ofString(jsonBody, StandardCharsets.UTF_8));

            // 3.组装请求头
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(requestBuilder::header);
            }

            // 4.发送post请求获取返回结果
            HttpResponse<String> response = mqHttpRequester.httpClient
                    .send(requestBuilder.build(), HttpResponse.BodyHandlers.ofString());

            // 5.检查响应状态
            if (response.statusCode() < 200 || response.statusCode() >= 300) {
                throw new RuntimeException("HTTP请求失败: 状态码 = " + response.statusCode());
            }

            // 6.将返回结果转换为目标类型
            return MqJsonConverter.convertJsonToGenericObject(response.body(), typeRef);
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }

}
